function detectVersion() {
  let isAndroid,
    isIOS,
    isIOS9,
    version,
    u = navigator.userAgent,
    ua = u.toLowerCase();

  if (u.indexOf("Android") > -1 || u.indexOf("Linux") > -1) {
    //android终端或者uc浏览器
    //Android系统
    isAndroid = true;
  }

  if (ua.indexOf("like mac os x") > 0) {
    //ios
    var regStr_saf = /os [\d._]*/gi;
    var verinfo = ua.match(regStr_saf);
    version = (verinfo + "").replace(/[^0-9|_.]/gi, "").replace(/_/gi, ".");
  }
  var version_str = version + "";
  if (version_str != "undefined" && version_str.length > 0) {
    version = parseInt(version);
    if (version >= 8) {
      // ios9以上
      isIOS9 = true;
    } else {
      isIOS = true;
    }
  }
  return { isAndroid, isIOS, isIOS9 };
}

// 判断手机上是否安装了app，如果安装直接打开url，如果没安装，执行callback
function openApp(url, callback) {
  let { isAndroid, isIOS, isIOS9 } = detectVersion();
  if (isAndroid || isIOS) {
    var timeout,
      t = 1500,
      hasApp = true;
    var openScript = setTimeout(function() {
      if (!hasApp) {
        if (callback) {
          callback();
        } else {
          alert(`没有找到应用，跳转下载`);
          goConfirmAddr();
        }
      }
      document.body.removeChild(ifr);
    }, 2000);

    var t1 = Date.now();
    var ifr = document.createElement("iframe");
    ifr.setAttribute("src", url);
    ifr.setAttribute("style", "display:none");
    document.body.appendChild(ifr);

    timeout = setTimeout(function() {
      var t2 = Date.now();
      if (t2 - t1 < t + 100) {
        hasApp = false;
      }
    }, t);
  }

  if (isIOS9) {
    location.href = url;
    setTimeout(function() {
      if (callback) {
        callback();
      } else {
        alert(`没有找到应用，跳转下载`);
        goConfirmAddr();
      }
    }, 250);
    setTimeout(function() {
      location.reload();
    }, 1000);
  }
}

function getKey(name) {
  let _i = decodeURIComponent((new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(location.href) || [, ""])[1].replace(/\+/g, "%20")) || null;
  if (name == "i") {
    return String(_i).replace(/[^0-9]/gi, ""); //过滤i非数字
  } else {
    return _i;
  }
}

//跳h5
function goConfirmAddr() {
  try {
    let _Domain  = document.location.protocol + "//" + window.location.host;//域名
    let _i = getKey('i');//平台id
    let _download = `${_Domain}/addons/yun_shop/?menu#/downloadUpdate?i=${_i}`;
    window.location.href = _download;
  } catch (error) {
    console.log("goConfirmAddr",error);
  }

}

export { openApp,goConfirmAddr };